package cn.mumzone.basic.mvp;


import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Author Chaney
 * Date   2017/3/7 下午3:03.
 * EMail  qiuzhenhuan.hi@gmail.com
 */

public abstract class AbsPresenter<T extends BaseView, R extends BaseRepository> implements BasePresenter<T> {

    protected T mView;
    protected R mRepo;

    private CompositeSubscription mCompositeSubscription;

    public AbsPresenter() {
        initRepository();
        initOtherRepository();
        if (mRepo == null) {
            throw new RuntimeException("Repository can't be Null!");
        }
    }

    protected void initRepository() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] types = ((ParameterizedType) type).getActualTypeArguments();
            Class<R> repoClass = (Class<R>) types[1];
            if (repoClass != null) {
                try {
                    mRepo = repoClass.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    protected void initOtherRepository() {
    }


    protected void addSubscrebe(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }

    protected void unSubscrebe() {
        if (mCompositeSubscription != null) {
            mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    public void attachView(T view) {
        this.mView = view;
    }


    @Override
    public void detachView() {
        this.mView = null;
        unSubscrebe();
    }

}
